//
//  WBHomeViewController.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/12.
//  Copyright © 2016年 木木. All rights reserved.
//

/*
 
 -MVC
 - vc
 - tableView   [HMStatus]
 - cell    HMStatus
 -------------------------------------------
 
 - 只是处理tableView 数据
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatus])
 - cell    ---  HMStatus
 
 -------------------------------------------
 
 
 - 处理cell的viewmodel 和tableView [viewmodel]
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatusCellViewModel])
 - cell    ---  HMStatusCellViewModel(HMStatus)
 
 */


import UIKit
import SVProgressHUD
import YYModel

let orgainalCellID = "WBHomeViewCell"
let retweetedCellID = "WBRetwwerViewCell"
let navBarHight:CGFloat = 64
class WBHomeViewController: WBBaseTableViewController {

    lazy var homeViewModel: WBHomeViewModel? = WBHomeViewModel()
    lazy var user :WBUserAccessViewModel? = WBUserAccessViewModel()
    lazy var WBrefreshControl:WBRefreshView = WBRefreshView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.tabBarController!.view.backgroundColor = UIColor.orange
        if  !((user?.userLogin)!){
        
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sweepBtn)
            visitorView.updataInfo(imageName: "visitordiscover_feed_image_smallicon", title: "被时代看的那空间是大家看到就看上的就看上打不死就看不到就看到就看谁快",isHome: true)
            return
        }
        
        //加载数据
        loadData()
        setupUI()
        
    }
    
    func setupUI(){
        //        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
        let orginalNibName = UINib(nibName: "WBHomeViewCell", bundle: nil)
        self.tableView.register(orginalNibName, forCellReuseIdentifier: orgainalCellID)
        let retweetedNibName = UINib(nibName: "WBRetwwerViewCell", bundle:nil)
        self.tableView.register(retweetedNibName, forCellReuseIdentifier: retweetedCellID)
        // 上啦    //下拉  控件
        tableView.tableFooterView = indicator
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
      
        WBrefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
          self.view.addSubview(WBrefreshControl)
        
        let  Y: CGFloat = navBarHight - 35
        lblText.frame = CGRect(x: 0, y: Y, width: USC_width, height: 35)
        //添加
       self.navigationController?.view.insertSubview(lblText, belowSubview: (self.navigationController?.navigationBar)!)
        
        
        self.tableView.separatorStyle = .none

    }
    
    //创建小菊花
    lazy var indicator:UIActivityIndicatorView = {
        let ind = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        
        return ind
    }()
    
    func loadData(){
        
        homeViewModel?.getData(isPluup: indicator.isAnimating) { (isSuccess,count) in
            if   !isSuccess {
                return
            }
            //得到数据
            self.indicator.stopAnimating()
            self.getAnimationLbl(count: count)
//            print("<<<-\(count)")
//            self.refreshControl?.endRefreshing()
            self.WBrefreshControl.endRefreshing()
            self.tableView.reloadData()
        }
        
        
    }
    func  getAnimationLbl(count:Int){
        if lblText.isHidden == false {
            return
        }
       
        self.lblText.backgroundColor = UIColor.orange
        let text = (count == 0 ? "没有新的微博" : "有\(count)条微博刷新")
        self.lblText.text = text
        self.lblText.isHidden = false
        //动画
        let lblY:CGFloat = lblText.frame.origin.y
        UIView.animate(withDuration: 1.0, animations: {
            self.lblText.frame.origin.y = navBarHight
        }, completion: { (_) in
            
            UIView.animate(withDuration: 1.0, delay: 1, options: [], animations: {
                 self.lblText.frame.origin.y = lblY
            }, completion: { (_) in
                self.lblText.isHidden = true
            })
        })
        
    }
    
    lazy var lblText:UILabel = {
        let lbl = UILabel(title: " ", titleColor: UIColor.white, font: UIFont.systemFont(ofSize: 16))
        lbl.textAlignment = .center
        lbl.isHidden = true
        
        return lbl
    }()
    

    lazy var sweepBtn : UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "navigationbar_pop"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "navigationbar_pop_highlighted"), for: .highlighted)
        
        btn.sizeToFit()
        btn.addTarget(self, action: #selector(push), for: .touchUpInside)
        return btn
    }()
    
    @objc private func push() {
        
        let VC = WBTextViewController()
        
        self.navigationController?.pushViewController(VC, animated: true)
        
    }
}
//MARK:  -
//MARK:  - dalegate
extension WBHomeViewController{
   
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (homeViewModel?.modelViewArr.count)!
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewMode = homeViewModel?.modelViewArr[indexPath.row]
        let cellID = getCellId(model: viewMode)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as!WBHomeViewCell
        
        cell.viewModel = viewMode
        
        return cell
    }
    func getCellId(model:WBStatuesViewModel?)->String{
        return model?.viewmodel?.retweeted_status == nil ? orgainalCellID : retweetedCellID
    }
    //MARK:
    // MARK: - 自动计算行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //取到cell
        let viewMode = homeViewModel?.modelViewArr[indexPath.row]
        let cellID = getCellId(model: viewMode)
        //        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as!WBHomeViewCell
        let cellNIbName = UINib(nibName: cellID, bundle: nil)
        //实例化cell
        let cell = cellNIbName.instantiate(withOwner: nil, options: nil).last as! WBHomeViewCell
  
        cell.viewModel = viewMode
        cell.layoutIfNeeded()
        return cell.toolbar.frame.maxY
        
    }
    

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if  indicator.isAnimating == false && indexPath.row == (homeViewModel?.modelViewArr.count)! - 2 {
            indicator.startAnimating()
            print("菊花开始转动了")
            loadData()
        }
        
    }
    
    
    
    

}







